package com.pipi.sso.web.controller;

import com.alibaba.fastjson.JSON;
import com.pipi.sso.core.enums.DormErrorCodeEnum;
import com.pipi.sso.core.model.BizResult;
import com.pipi.sso.core.model.MenuBO;
import com.pipi.sso.core.model.UserBO;
import com.pipi.sso.core.service.MenuService;
import com.pipi.sso.web.shiro.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

/**
 * All rights Reserved, Designed By www.maihaoche.com
 *
 * @Package com.pipi.sso.web.controller
 * @date: 2019/3/29 4:32 PM
 * @Copyright: 2017-2020 www.maihaoche.com Inc. All rights reserved.
 */
@Controller
@Slf4j
public class IndexController {

    @Resource
    HttpSession session;

    @Resource
    private MenuService menuService;

    @Resource
    private UserInfoService userInfoService;

    @RequestMapping("/index.json")
    public String index(Model model) {

        List<MenuBO> menuBOS = menuService.queryAllMenu();
        UserBO currentUser = userInfoService.getCurrentUser();
        String roleCode = currentUser.getRole().getRoleCode();
        model.addAttribute("menu", checkRole(menuBOS, roleCode));
        model.addAttribute("user", currentUser);
        return "index/index";
    }

    @RequestMapping("welcome.json")
    public String welcome() {
        return "index/welcome";
    }

    private List<MenuBO> checkRole(List<MenuBO> menuBOS, String roleCode) {
        return menuBOS.stream().filter(menuBO -> {
            if (menuBO.getRoleCode().contains(roleCode)) {
                if (CollectionUtils.isNotEmpty(menuBO.getChildrenMenu())) {
                    List<MenuBO> childMenu = checkRole(menuBO.getChildrenMenu(), roleCode);
                    menuBO.setChildrenMenu(childMenu);
                }
                return true;
            }
            return false;
        }).collect(Collectors.toList());
    }

    @RequestMapping("toLogin.json")
    public String toLogin() {
        return "login/login";
    }

    @RequestMapping(value = "login.json", method = RequestMethod.POST)
    @ResponseBody
    public BizResult<String> login(@RequestBody UserBO userBO) {
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                userBO.getUsername(),
                userBO.getPassword());
        //进行验证，这里可以捕获异常，然后返回对应信息
        try {
            subject.login(usernamePasswordToken);
            session.setAttribute("user", userBO.getUsername());
            return BizResult.create(userBO.getUsername());
        } catch (Exception e) {
            log.error("登陆失败！userBO is {}", JSON.toJSONString(userBO), e);
            return BizResult.create(DormErrorCodeEnum.EXCEPTION.getErrMsg(), e.getMessage());
        }
    }


    @RequestMapping("/logout.json")
    public String logout() {
        userInfoService.logout();
        return "login/login";
    }

    @RequestMapping("chat.json")
    public String chat(Model model) {
        model.addAttribute("user", userInfoService.getCurrentUser());
        return "index";
    }
}
